/**
 * Created by tanbingqin on 2019/1/25.
 */
import React from 'react'
import { connect } from 'react-redux';
import moment from 'moment'
import CustomTable from 'components/custom-table'
import {messages, deepCopy, deepFullCopy, queryCurrencyPrecision} from 'share/common'
import {Input, Row, Col, Table, Popover, Affix, Button, message} from 'antd'

class ExpenseTypeClose extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      expenseList: [],
      showExpenseFlag: false,
      nowExpense: {},
      columns: [
        {
          title: '',
          dataIndex: 'id',
          width: '5%',
          render: (value, record) => <img src={record.expenseType.iconURL} style={{width: 20, maxHeight: 20}}/>
        },
        {
          title: messages('components.key379'/*费用类型*/), dataIndex: 'expenseType', render: value =>
          <Popover content={value.name}>{value.name}</Popover>
        },
        {title: messages('components.key380'/*币种*/), dataIndex: 'currencyCode',width: 48},
        {title: messages('components.key381'/*金额*/), dataIndex: 'amount', align: 'right',width: '7%',render: (value, record)=>this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))},
        {title: messages('components.key382'/*汇率*/), dataIndex: 'actualCurrencyRate',align: 'right', width: '10%',render: value => this.filterMoney(value || 1, 2)},
        {
          title: messages('components.key148'/*本币金额*/), dataIndex: 'baseAmount', align: 'right',width: '8%',render: (value, record) =>
          this.filterMoney((record.amount * record.actualCurrencyRate).toFixed(4), queryCurrencyPrecision(props.info.currencyCode))
        }
      ],
      selectedBudgetRowKeys: [], //选中的预算行oid
      selectedApportionRowKeys: [], //选中的分摊行oid
      childrenColumns: []
    }
  }

  componentWillMount() {
    //切换审批历史和申请单信息的时候会重新加载dom
    if (this.props.info && this.props.info.custFormValues) {
      this.initExpenseField(this.props.info.custFormValues);
    }
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.info && nextProps.info.custFormValues) {
      this.initExpenseField(nextProps.info.custFormValues);
    }
  };

  //初始化预算明细列表
  initExpenseField = (custFormValues) => {
    custFormValues.map(item => {
      if (item.messageKey === 'budget_detail' && item.showValue) {
        this.setState({expenseList: JSON.parse(item.showValue || '{}').budgetDetail}, () => {
          this.initExpenseList();
        });
      }
    });
  };

  //封装expenseList展示用数据
  initExpenseList = () => {
    let {expenseList} = this.state;
    let costCenterItems = [];
    let isGetCostCenterItems = false;//获取一次costCenterItems就可以了，每个costCenterItems展示顺序是一样的
    expenseList.map(expense => {
      if (expense.apportionmentDTOList && expense.apportionmentDTOList.length) {
        expense.apportionmentDTOList.map(apportionment => {
          //把预算行上的币种信息写入到分摊行上
          apportionment.currencyCode = expense.currencyCode;
          //把分摊项的名称写到分摊行上
          apportionment.costCenterItems && apportionment.costCenterItems.map((item, index) => {
            apportionment[`costCenterItem${index}`] = item.name;
          });
          if (!isGetCostCenterItems) {
            costCenterItems = JSON.parse(JSON.stringify(apportionment.costCenterItems));
            isGetCostCenterItems = true;
          }
        });
      }
    });
    this.initChildrenColumns(costCenterItems);
    this.setState({expenseList});
  };

  initChildrenColumns = (costCenterItems) => {
    let childrenColumns = [];
    costCenterItems && costCenterItems.map((item, index) => {
      childrenColumns.push({
        title: item.fieldName,
        dataIndex: `costCenterItem${index}`,
        render: value => value ? <Popover placement="topLeft" content={value} overlayStyle={{maxWidth: 500}}>{value}</Popover> : '-'
      });
    });
    let fixedArray = [
      {
        title: messages('request.key551')/*原币金额*/,
        dataIndex: 'amount',
        align: 'right',
        width: '10%',
        render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
      },
      {
        title: messages('request.key230')/*本币金额*/,
        dataIndex: 'baseCurrencyAmount',
        align: 'right',
        width: '10%',
        render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(this.props.info.currencyCode))
      },
      {
        title: messages('request.key552')/*原币已报销*/,
        dataIndex: 'reimbursementAmount',
        align: 'right',
        width: '10%',
        render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
      },
      {
        title: messages('request.key553')/*本币已报销*/,
        dataIndex: 'baseReimbursementAmount',
        align: 'right',
        width: '10%',
        render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(this.props.info.currencyCode))
      }
    ];
    childrenColumns = childrenColumns.concat(fixedArray);
    this.setState({childrenColumns});
  };

  //分摊行列表选择更改
  onSelectApportionChange = (selectedRowKeys) => {
    this.setState({ selectedApportionRowKeys: selectedRowKeys }, () => {
      //此处this.state.selectedBudgetRowKeys并不是最新的，此次选择的分摊行的预算行可能不包括在内(取决于this.setState)，但是因为分摊行可操作，就不需要预算行了
      this.props.changeHandle(this.state.selectedApportionRowKeys, this.state.selectedBudgetRowKeys);
    });
  };

  //选择一行分摊行
  onSelectApportionRow = (record, selected, selectedRows) => {
    let selectedRowKeys = deepFullCopy(this.state.selectedBudgetRowKeys);
    let budgetOID = record.budgetOID;
    let currentExpenseLength = 0; //当前预算行下的可关闭的分摊行的数量
    this.state.expenseList.map(item => {
      if (item.budgetOID === budgetOID) {
        item.apportionmentDTOList && item.apportionmentDTOList.map(apportion => {
          if (apportion.budgetClosed !== 1003 && apportion.budgetClosed !== 1002) {
            currentExpenseLength++;
          }
        });
      }
    });
    if (selectedRows.length > 0 && selectedRows.length === currentExpenseLength) {
      selectedRowKeys.addIfNotExist(budgetOID);
    } else {
      selectedRowKeys.delete(budgetOID);
    }
    this.setState({ selectedBudgetRowKeys: selectedRowKeys });
  };

  //全选分摊行
  onSelectAllApportionRow = (selected, selectedRows, changeRows) => {
    let selectedRowKeys = deepFullCopy(this.state.selectedBudgetRowKeys);
    let budgetOID = changeRows.length ? changeRows[0].budgetOID : ''; //得从changeRows里获取，不然取消全选的时候获取不到值
    selected ? selectedRowKeys.addIfNotExist(budgetOID) : selectedRowKeys.delete(budgetOID);
    this.setState({ selectedBudgetRowKeys: selectedRowKeys });
  };

  //渲染table的子行
  expandedRowRender = (record, index) => {
    const {childrenColumns, selectedApportionRowKeys} = this.state;
    const apportionRowSelection = {
      selectedRowKeys: selectedApportionRowKeys,
      onChange: this.onSelectApportionChange,
      onSelect: this.onSelectApportionRow,
      onSelectAll: this.onSelectAllApportionRow,
      getCheckboxProps: record => ({
        disabled: record.budgetClosed === 1003 || record.budgetClosed === 1002 //1003已关闭，1002无剩余预算
      })
    };
    return (record.apportionmentDTOList && record.apportionmentDTOList.length) ? (
      <div>
        <CustomTable allColumns={childrenColumns}
                     localKey={`${this.props.info.applicationOID}-close-list`}
                     tableOption={{
                       rowKey:'apportionmentOID',
                       size:'middle',
                       pagination: false,
                       rowSelection: window.ISIE9 ? null : apportionRowSelection,
                       columns: childrenColumns,
                       bordered: true,
                       dataSource: record.apportionmentDTOList
                     }}/>
      </div>
    ) : null
  };

  //预算行列表选择更改
  onSelectBudgetChange = (selectedRowKeys) => {
    this.setState({ selectedBudgetRowKeys: selectedRowKeys });
  };

  //选择一行预算行
  onSelectBudgetRow = (record, selected, selectedRows) => {
    let selectedRowKeys = deepFullCopy(this.state.selectedApportionRowKeys);
    record.apportionmentDTOList && record.apportionmentDTOList.map(apportion => {
      if (apportion.budgetClosed !== 1003 && apportion.budgetClosed !== 1002) {
        selected ? selectedRowKeys.addIfNotExist(apportion.apportionmentOID) : selectedRowKeys.delete(apportion.apportionmentOID);
      }
    });
    let selectedBudgetRowKeys = [];
    selectedRows && selectedRows.map(budget => {
      selectedBudgetRowKeys.push(budget.budgetOID);
    });
    this.setState({ selectedApportionRowKeys: selectedRowKeys }, () => {
      this.props.changeHandle(this.state.selectedApportionRowKeys, selectedBudgetRowKeys);
    });
  };

  //全选预算行
  onSelectAllBudgetRow = (selected, selectedRows) => {
    let selectedRowKeys = deepFullCopy(this.state.selectedApportionRowKeys);
    this.state.expenseList.map(item => {
      //手动触发对每一行的操作
      //this.onSelectBudgetRow(item, selected); 不能这样操作，否则selectedApportionRowKeys更新会有问题
      item.apportionmentDTOList && item.apportionmentDTOList.map(apportion => {
        if (apportion.budgetClosed !== 1003 && apportion.budgetClosed !== 1002) {
          selected ? selectedRowKeys.addIfNotExist(apportion.apportionmentOID) : selectedRowKeys.delete(apportion.apportionmentOID);
        }
      });
    });
    let selectedBudgetRowKeys = [];
    selectedRows && selectedRows.map(budget => {
      selectedBudgetRowKeys.push(budget.budgetOID);
    });
    this.setState({ selectedApportionRowKeys: selectedRowKeys }, () => {
      this.props.changeHandle(this.state.selectedApportionRowKeys, selectedBudgetRowKeys);
    });
  };

  render() {
    const {columns, expenseList, selectedBudgetRowKeys} = this.state;
    const budgetRowSelection = {
      selectedRowKeys: selectedBudgetRowKeys,
      onChange: this.onSelectBudgetChange,
      onSelect: this.onSelectBudgetRow,
      onSelectAll: this.onSelectAllBudgetRow,
      getCheckboxProps: record => ({
        disabled: record.budgetClosed === 1003 || record.budgetClosed === 1002 //不可关闭状态时不可勾选，没有分摊行也可以关闭
      })
    };
    return (
      <div style={{float: 'left'}}>
        <Table rowKey="budgetOID"
               columns={columns}
               dataSource={expenseList}
               expandedRowRender={this.expandedRowRender}
               rowSelection={budgetRowSelection}
               rowClassName={record => (record.apportionmentDTOList && record.apportionmentDTOList.length) ? '' : 'row-expand-display-none'}
               pagination={false}
               bordered
               size="middle"/>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}

ExpenseTypeClose.propTypes = {
  info: React.PropTypes.object,
  changeHandle: React.PropTypes.func
};

ExpenseTypeClose.defaultProps = {
  info: {}
};

export default connect(mapStateToProps)(ExpenseTypeClose)
